/**
 * Created by hjqi on 2016/3/3.
 */
angular.module('NatureCloud').controller('VerModifyController',
    function ($scope,$rootScope,$state, $cookies,$stateParams,$mdDialog,dockerRegisterService,k8sService,UpdateInsertDB,params, /*Alertify,*/utilService,svcCommonService,$http) {

        var _version,_imgurl;
        var item = params.data.dbJson;
        _version = item.ver;
        _imgurl = item.node.image;
        $scope.datas=params.data;
        //$scope.TestVerPer=undefined;

        //var _version = item.imageversion;

        dockerRegisterService.getTagFromRegistry(_imgurl).then(function (response) {
            $scope.datas = response.data;
            if(response.data.indexOf(_version) != -1) {
                $scope.SelectedVer = _version;
                $scope.VersionToAdd= _version;
                $scope.data= params.data;
                $scope.TestVer=item.rc_test==null?null:item.rc_test.metadata.labels.version;
            }
        }, function (response) {
                //err flow
            console.log("Can't get tags. data="+ response.data) ;
            alertify.error("Can not get tags!") ;
        });

        $scope.ok = function(){

            var _id = item.app;
            var _newVer = $scope.SelectedVer;
            var _oldVer,_oldReplicas,_oldRc;
            _oldVer = item.ver;

            if(item.id === undefined){
                item.ver = _newVer;
                var _last = item.node.image.lastIndexOf(':');
                item.node.image = item.node.image.substr(0,_last+1) + _newVer;
                alertify.success('id:'+_id+', has success upgrade from ['+_oldVer+'] to ['+_newVer+']');
                $mdDialog.hide();
            }else{

                if(_oldVer !== _newVer){

                    k8sService.updateServiceStatus(params.data,"updating").then(function(){
                        params.data.totalStatue = 'updating';
                        svcCommonService.setIconClass(params.data);
                        //change the data to new version


                        k8sService.grayupdate(item,_newVer).then(function(response){
                            //if(response.status === 200 && response.data === 'true'){
                            //assume return 200 is grayupdate success
                            if(response.status === 200){
                                //update throw get pod in service list
                                //item is old version

                                //if return success ,need to change rc to new rc
                                params.data.ver = _newVer ;
                                params.data.dbJson.rc = response.data.rc;
                                $rootScope.$emit('udpSvcInfoWhenUpdate',params.data);
                                //alertify.success( " service [" + data.app + "] update success!");
                            }else{
                                //update status and icon
                                params.data.totalStatue = 'error';
                                svcCommonService.setIconClass(params.data);

                                alertify.error('id:'+_id+', upgrade from ['+_oldVer+'] to ['+_newVer+'] failed');
                                $rootScope.$emit('udpSvcInfoWhenUpdate',params.data);
                            }
                        },function(response){
                            //err flow
                            //_newRc.spec.template.metadata.labels.version = _version;
                            $scope.SelectedVer = _version;
                            console.log( 'upgrade error,'+'id:'+_id+', upgrade from ['+_oldVer+'] to ['+_newVer+'] </br>'+JSON.stringify( response.data) ) ;
                            alertify.alert('upgrade error','Service:'+_id+', upgrade from ['+_oldVer+'] to ['+_newVer+'] failed</br>' );
                        });
                    },function(){
                        //update db error
                        //need to retry
                    });
                    $mdDialog.hide();
                }
            }
        };
        $scope.setVersionChoice=function(choice){
            $scope.NewVer=choice;
        };
        $scope.addVersion=function(VersionToAdd){
            $scope.NewVer=false;
            k8sService.addTestVersionForSvc(item.node.clusterId,item.app,item.ver,VersionToAdd).then(function(val){
                $scope.TestVer=val.data.metadata.labels.version;
            });
        };
        $scope.updateVersion=function(){

            k8sService.publishTestVersionRc(item.node.clusterId,item.app).then(function(val){
                $scope.NewVer=false;
                $scope.TestVer=false;
                item.ver=$scope.SelectedVer=val.data.metadata.labels.version;
            });
        };
        $scope.removeVersion=function(VersionToRemove){
            $scope.TestVer=false;
            $scope.NewVer=false;
            k8sService.deleteTestVersionForSvc(item.node.clusterId,item.app);
        };

        $scope.setTestVerPer=function(per){
            console.log(typeof per);
            $http({
                url:'/trafficRule/set',
                method:'POST',
                data:{
                    "serviceName":params.data.id,
                    "version":params.data.imageVersion,
                    "weight":per
                }
            }).success(function(data,header,config,status){

            }).error(function(data,header,config,status){

            });
        }
        $scope.cancel = function(){
            $mdDialog.cancel();
        };

        $scope.toServiceUpdate = function() {
            $mdDialog.hide();
            $state.go('cp.serviceupdate', {service:params.data,serviceName: params.data.app});
        }

    }
);